package com.felix.datasources;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.HashMap;
import java.util.Map;

/**
 * 配置多数据源
 *
 * @author xuejinhua
 * @date 2017/8/19 0:41
 */
@Slf4j
@Configuration
public class DynamicDataSourceConfig {


    @Autowired
    private DataSourcesProperties properties;

    @Bean(name = "dataSource")
    public DynamicDataSource dataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceNames.SLAVE, properties.getMaster());
        targetDataSources.put(DataSourceNames.MASTER, properties.getSlave());
        // 设置默认数据源
        return new DynamicDataSource(properties.getMaster(), targetDataSources);
    }
    /**
     * 注入 DataSourceTransactionManager 用于事务管理
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

}
